import axios from "axios";
import { Message } from "element-ui";
import { getToken, setToken, removeToken } from '@/utils/token';

// axios 配置
const service = axios.create({
  headers: {"Content-Type": "application/json"},
  timeout: 30000
});

// 添加请求拦截器
service.interceptors.request.use(
  config => {
    config.headers["token"] = getToken();
    return config;
  },
  error => {
    // 对请求错误做些什么
    console.log(error);
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.status === 40101) {// token过期
      removeToken();
      Message.error("Token已过期");
    }
    return res;
  },
  error => {
    return Promise.reject(error);
  }
);

/**
 * get 请求方法
 * @param data {url: '', params:{id: '', name: ''}}
 * @returns {Promise}
 */
export function get(data) {
  return new Promise((resolve, reject) => {
    service.get(data.url, { params: data.params ? data.params : {} }).then(response => {
        resolve(response);
      }).catch(err => {
        reject(err);
      });
  });
}

/**
 * post 请求方法
 * @param data {url: '', params:{id: '', name: ''}}
 * @returns {Promise}
 */
export function post(data) {
  return new Promise((resolve, reject) => {
    service.post(data.url, data.params).then(
      response => {
        resolve(response);
      },
      err => {
        reject(err);
      }
    );
  });
}

/**
 * 封装所有请求
 * @param data {method: '', url: '', params:{id: '', name: ''}, headers: {}}
 * @returns {Promise}
 */
export function request(data) {
  return new Promise((resolve, reject) => {
    service({
      method: data.method || "post",
      url: data.url,
      params: data.method === "get" ? data.params : "",
      data: data.method !== "get" ? data.params : "",
      headers: data.headers || { "Content-Type": "application/json" }
    })
      .then(response => {
        resolve(response);
      })
      .catch(err => {
        reject(err);
      });
  });
}

export default service;
